package com.business_clean.app.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.business_clean.app.App;
import com.business_clean.app.config.Constant;
import com.business_clean.app.network.NetUrl;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.UploadFileHelper;
import com.business_clean.data.mode.leader.CustomMarkLeaderData;
import com.luck.picture.lib.BuildConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectorConfig;
import com.luck.picture.lib.config.SelectorProviders;
import com.luck.picture.lib.service.ForegroundService;
import com.luck.picture.lib.utils.SdkVersionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;
import me.hgj.mvvmhelper.ext.LogExtKt;
import okhttp3.Response;
import rxhttp.wrapper.param.RxHttp;

/**
 * 图片视频 标记 - 上报的服务
 */
public class MarkUploadService extends Service {

    private static final String CHANNEL_ID = AppUtils.getAppPackageName() + "." + ForegroundService.class.getName();
    private static final String CHANNEL_NAME = AppUtils.getAppPackageName();
    private static final int NOTIFICATION_ID = 1;

    private static boolean isForegroundServiceIng = false;


    private static MarkUploadService instance;

    public static MarkUploadService getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        Notification notification = createForegroundNotification();
        startForeground(NOTIFICATION_ID, notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        MarkUploadService.isForegroundServiceIng = true;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        MarkUploadService.isForegroundServiceIng = false;
        stopForeground(true);
        super.onDestroy();
    }


    /**
     * 在这里做判断视频还是标记
     *
     * @param message_type
     * @param waterUrl
     * @param original
     */
    public void uploadFile(int act_type, int message_type, double lat, double lnt, String address,
                           String waterUrl, String original,
                           List<CustomMarkLeaderData> attendance_data, long takePhotoMills) {
        if (1 == message_type) {//图片
            if (!TextUtils.isEmpty(waterUrl) && !TextUtils.isEmpty(original)) {
                if (!TextUtils.isEmpty(waterUrl) && !TextUtils.isEmpty(original)) {
                    UploadFileHelper.getInstance().uploadPictures(this, waterUrl, UploadFileHelper.PATH_HEADER_CAMERA, new UploadFileHelper.UploadListener() {
                        @Override
                        public void onUploadSuccess(String waterResponse) {
                            UploadFileHelper.getInstance().uploadPictures(instance, original, UploadFileHelper.PATH_HEADER_CAMERA, new UploadFileHelper.UploadListener() {
                                @Override
                                public void onUploadSuccess(String originalResponse) {
                                    // 分别上传水印图片和原图成功后，再发送请求
                                    requestMark(act_type, message_type, lat, lnt, address, waterResponse, originalResponse, attendance_data, takePhotoMills);
                                }

                                @Override
                                public void onUploadFailed(String error) {
                                    ToastUtil.show("上传原图失败" + error);
                                }

                                @Override
                                public void onUploadProgress(int progress) {
                                    // 原图上传进度
                                }
                            });
                        }

                        @Override
                        public void onUploadFailed(String error) {
                            ToastUtil.show("上传水印图片失败" + error);
                        }

                        @Override
                        public void onUploadProgress(int progress) {
                            // 水印图片上传进度
                        }
                    });
                }
            }
        } else if (2 == message_type) {
            if (!TextUtils.isEmpty(waterUrl)) {//视频
                UploadFileHelper.getInstance().uploadPictures(this, waterUrl, UploadFileHelper.PATH_HEADER_CAMERA, new UploadFileHelper.UploadListener() {
                    @Override
                    public void onUploadSuccess(String response) {
                        requestMark(act_type, message_type, lat, lnt, address, response, null, attendance_data, takePhotoMills);
                    }

                    @Override
                    public void onUploadFailed(String error) {
                        ToastUtil.show("上传失败" + error);
                    }

                    @Override
                    public void onUploadProgress(int progress) {

                    }
                });
            }
        }
    }


    /**
     * 标记上报
     */
    private void requestMark(int act_type, int message_type, double lat, double lnt, String address, String waterUrl, String original, List<CustomMarkLeaderData> attendance_data, Long takePhotoMills) {
        LogExtKt.logE("标记图片原图地址:" + original, "");
        LogExtKt.logE("标记图片水印地址:" + waterUrl, "");
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("act_type", "" + act_type);//操作类型 1日常工作 2领班打卡
        hashMap.put("message_type", "" + message_type);//消息类型 1图片消息 2视频
        hashMap.put("origin_media_url", "" + original);//消息媒体地址(无水印)
        hashMap.put("project_uuid", App.appViewModelInstance.getProjectInfo().getValue().getUuid());
        hashMap.put("media_url", "" + waterUrl);//消息媒体地址(有水印)
        hashMap.put("address", "" + address);
        hashMap.put("lnt", "" + lnt);
        hashMap.put("lat", "" + lat);
        hashMap.put("take_photo_time", "" + (takePhotoMills / 1000));//拍照时间
        hashMap.put("security_code", "" + takePhotoMills);//防伪码
        if (attendance_data != null && attendance_data.size() > 0) {
            hashMap.put("attendance_data", JSON.toJSONString(attendance_data));
        }
        RxHttp.get(NetUrl.MARK_PHOTO).addAll(hashMap).asOkResponse().subscribe(new Consumer<Response>() {
            @Override
            public void accept(Response response) throws Throwable {

            }
        });
    }

    /**
     * 创建前台通知Notification
     *
     * @return
     */
    private Notification createForegroundNotification() {
        int importance = 0;
        if (SdkVersionUtils.isMaxN()) {
            importance = NotificationManager.IMPORTANCE_HIGH;
        }
        if (SdkVersionUtils.isO()) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
            channel.setLightColor(Color.BLUE);
            channel.canBypassDnd();
            channel.setBypassDnd(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);
        }
        String contentText = "正在图片上传";
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(com.luck.picture.lib.R.drawable.ps_ic_trans_1px)
                .setContentTitle(AppUtils.getAppPackageName())
                .setContentText(contentText)
                .setOngoing(true)
                .build();
    }

}
